// pages/Users/AddPet/AddPet.js
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryPetSpecies , queryAllPetBreed , updatePetInfo } from '../../../api/pet';
import { formatTime } from '../../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    uploadFileUrl: app.globalData.global.uploadFileUrl,
    brandId: app.globalData.global.brandId,
    imageUrl: '', // 宠物头像
    nickname: '', // 宠物昵称
    sex: '0',
    sterilization: '1',
    breedId: '', // 品种ID
    breedName: '', // 品种名称
    speciesId: '', // 种类ID
    birthDate: '', // 出生日期
    weight: '', // 体重
    showBreed: false,
    breedList: [], // 品种列表
    showBirth: false,
    currentDate: new Date().getTime(),
    minDate: new Date(2020,1,1).getTime(),
    maxDate: new Date().getTime(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var _this = this;
    if (wx.onNeedPrivacyAuthorization) {
      wx.onNeedPrivacyAuthorization((resolve) => {
        console.log('触发弹窗')
        // 触发弹窗
        _this.setData({
          showPrivacyAuthor: true,
        })
        _this.resolvePrivacyAuthorization = resolve
      })
    }
    this.queryPetSpec();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let userId = wx.getStorageSync('userId') ?? 10;
    return {
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  handleAgreePrivacyAuthorizationFun(){
    console.log('同意之后的回调');
  },
  disagreePrivacyAuthorization(){
    this.resolvePrivacyAuthorization({ event: 'disagree' });
  },
  // 选择图片
  selImg(){
    let _this = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success(e){
        console.log(e.tempFiles)
        var token = wx.getStorageSync('access_token');
        wx.uploadFile({
          url: _this.data.uploadFileUrl, // 上传接口
          filePath: e.tempFiles[0].tempFilePath,
          name: 'file',
          formData: { 'brandId': _this.data.brandId ,'access_token': token,},
          success(res) {
            console.log(res,'res')
            var res = JSON.parse(res.data);
            if(res.success){
              _this.setData({ imageUrl: res.data });
            }else{
              wx.showToast({
                title: res.errMessage,
                icon: 'none',
              })
            }
          },
        });
      },
      fail: function(err){
        console.log(err,'err')
      }
    })
  },
  // 输入框
  onChange(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
    const name = event.target.dataset.name||event.currentTarget.dataset.name;
    console.log(name,'name')
    // this.setData({
    //     name: event.detail,
    // })
    var data = this.data;
    data[name] =  event.detail;
    this.setData(data);
  },
  // 切换选项
  selItem(event){
    console.log(event)
    const name = event.target.dataset.name||event.currentTarget.dataset.name;
    const item = event.target.dataset.item||event.currentTarget.dataset.item;
    var data = this.data;
    data[name] =  item;
    this.setData(data);
  },
  onClose(){
    this.setData({
      showBreed: false,
      showBirth: false,
    })
  },
  showBreedEnt(){
    this._queryPetBreed();
    this.setData({
      showBreed: true,
    })
  },
  // 查询宠物种类
  queryPetSpec(){
    let _this = this;
    queryPetSpecies({size: 99})
    .then(res => {
      if(res.success){
        _this.setData({
          specList: res.data.content,
          speciesId: res.data.content.length > 0 ? res.data.content[0].id : '',
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取宠物品种
  _queryPetBreed(){
    let _this = this;
    queryAllPetBreed({speciesId: _this.data.speciesId})
    .then(res => {
      if(res.success){
        _this.setData({
          breedList: res.data,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 切换宠物种类
  selSpec(event){
    const item = event.target.dataset.item||event.currentTarget.dataset.item;
    this.setData({
      speciesId: item.id,
    })
    this._queryPetBreed();
  },
  // 选择宠物品种
  selBreed(event){
    const item = event.target.dataset.item||event.currentTarget.dataset.item;
    this.setData({
      breedId: item.id,
      breedName: item.name,
      showBreed: false,
    })
  },
  // 选择出生时间
  showBirthEnt(){
    this.setData({
      showBirth: true,
    })
  },
  // 确认选择出生时间
  dateConfirm(event){
    console.log(event)
    var time = formatTime(event.detail,'Y-M-D');
    this.setData({
      birthDate: time,
      showBirth: false,
    })
  },
  // 取消
  back(){
    wx.navigateBack();
  },
  // 保存宠物信息
  updatePet(){
    let _this = this;
    const { imageUrl , nickname , sex , sterilization , speciesId , breedId , weight , birthDate } = _this.data;
    if(imageUrl == ''){
      wx.showToast({
        title: '请上传爱宠头像',
        icon: 'none;'
      })
      return;
    }
    if(nickname == ''){
      wx.showToast({
        title: '请填写爱宠昵称',
        icon: 'none;'
      })
      return;
    }
    if(weight == ''){
      wx.showToast({
        title: '请填写爱宠体重',
        icon: 'none;'
      })
      return;
    }
    if(breedId == ''){
      wx.showToast({
        title: '请选择爱宠品种',
        icon: 'none;'
      })
      return;
    }
    if(birthDate == ''){
      wx.showToast({
        title: '请选择爱宠出生时间',
        icon: 'none;'
      })
      return;
    }
    updatePetInfo({speciesId: speciesId,breedId: breedId,nickname: nickname,sex: sex,sterilization: sterilization,weight: weight,birthDate: birthDate,imageUrl: imageUrl,})
    .then(res => {
      if(res.success){
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        });
        const eventChannel = _this.getOpenerEventChannel()
        eventChannel.emit('updatePetInfo',);
        _this.back();
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
})